package com.mg.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mg.dto.SimpleResult;
import com.mg.mapper.MachineTypeMapper;
import com.mg.model.MachineType;
import com.mg.service.MachineTypeService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created by mg1213 on 2018/3/18.
 */
@Service
public class MachineTypeServiceImpl implements MachineTypeService {
    @Autowired
    private MachineTypeMapper machineTypeMapper;

    private Logger logger = LogManager.getLogger(MachineTypeServiceImpl.class.getName());

    @Override
    public PageInfo<MachineType> selectPageInfo(MachineType machineTypeDto, int start, int limit) {
        PageHelper.offsetPage(start, limit);

        List<MachineType> resultList = machineTypeMapper.selectPageInfo(machineTypeDto);
        PageInfo<MachineType> result = new PageInfo<>(resultList);
        return result;
    }

    @Override
    public SimpleResult insertMachineType(MachineType record) {
        SimpleResult result = new SimpleResult();
        try {
            record.setCreateTime(new Date());
            machineTypeMapper.insert(record);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("新增矿机类型信息失败 系统未知异常");
            logger.error("新增矿机类型信息失败 系统未知异常", e);
        }
        return result;
    }

    @Override
    public SimpleResult updateMachineType(MachineType record) {
        SimpleResult result = new SimpleResult();
        try {
            MachineType record1 = new MachineType();
            record1.setId(record.getId());
            record1 = machineTypeMapper.selectOne(record1);
            if (record1 == null) {
                result.setSuccess(false);
                result.setMsg("该矿机类型信息不存在，请刷新重试！");
            } else {

                record.setUpdateTime(new Date());
                machineTypeMapper.updateByPrimaryKeySelective(record);
            }

        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("更新矿机类型信息失败 系统未知异常");
            logger.error("更新矿机类型信息失败 系统未知异常", e);
        }
        return result;
    }

    @Override
    public SimpleResult deleteMachineType(String ids) {
        SimpleResult result = new SimpleResult();
        try {
            String[] idArr = ids.split(",");
            for (String id : idArr) {

                machineTypeMapper.deleteByPrimaryKey(Integer.parseInt(id));
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("删除矿机类型信息失败 系统未知异常");
            logger.error("删除矿机类型信息失败 系统未知异常", e);
        }
        return result;
    }
}
